const getJsonHandle = (val: string | null): any => {
  if (val === null) {
    return val;
  }
  try {
    // eslint-disable-next-line no-param-reassign
    val = JSON.parse(val);
  } catch (e) {}
  return val;
};

const setJsonHandle = (val: any) => {
  if (val instanceof Object) {
    // eslint-disable-next-line no-param-reassign
    val = JSON.stringify(val);
  }
  return val;
};

export const createStorage = <T>(key: string) => {
  const get = ()=>{
    return  getJsonHandle(localStorage.getItem(key));
  };
  return {
    get: (): T | null => {
      return get();
    },
    set: (val: T) => {
      localStorage.setItem(key, setJsonHandle(val));
    },
    remove: () => {
      localStorage.removeItem(key);
    },
    setPartial: (val: T) => {
      localStorage.setItem(key, setJsonHandle(Object.assign(get() ?? {}, val)));
    },
  };
};

const getGroupKey = (key: string,currentKey: string)=>{
  return `${key}:${currentKey}`;
}

export const createGroupStorage = <T>(key: string) => {
  const get = (currentKey: string)=>{
    return getJsonHandle(localStorage.getItem(getGroupKey(key, currentKey)));
  };
  return {
    get: (currentKey: string): T | null => {
      return get(currentKey);
    },
    set: (currentKey: string, val: T) => {
      localStorage.setItem(getGroupKey(key, currentKey), setJsonHandle(val));
    },
    remove: (currentKey: string) => {
      localStorage.removeItem(getGroupKey(key, currentKey));
    },
    setPartial: (currentKey: string, val: T) => {
      localStorage.setItem(getGroupKey(key, currentKey), setJsonHandle(Object.assign(get(currentKey) ?? {}, val)));
    },
  };
};
